package com.jt.provider.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 基于此Controller测试是否启用本地缓存的配置(这个配置从配置中心读取)
 */
@RefreshScope
@RestController
public class ProviderCacheController {

    @Value("${useLocalCache:false}")
    private boolean useLocalCache;

    @RequestMapping("/provider/cache01")
    public String doUseLocalCache01(){
        return "useLocalCache'value is   "+useLocalCache;
    }
    //---------------------------------------------------------
    //构建一个本地(Local)缓存对象(基于jvm中的一个对象存储从数据库获取的数据).
    private List<String> cache=new CopyOnWriteArrayList<>();
    @RequestMapping("/provider/cache02")
    public  List<String> doUseLocalCache02(){
        if(!useLocalCache){
            System.out.println("==Get data from database==");
            return Arrays.asList("Category-A", "Category-B", "Category-C");
        }
        if(cache.isEmpty()) {
            synchronized (cache) {
                if (cache.isEmpty()) {//Thread-A,Thread-B,...
                    System.out.println("==Get data from database==");
                    //假设这部分分类信息是从数据库获取的,但是,我不希望每次获取分类信息都要从数据库查
                    List<String> cates = Arrays.asList("Category-A", "Category-B", "Category-C");
                    cache.addAll(cates);
                }
            }
        }
        return cache;
    }//生产层面

}
